package MD.NJavaUnionAd;
import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTSplashAd;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import MD.NJavaBase.ICallbackLight;
import MD.NJavaBase.ISplashAd;
import MD.NJavaBase.NJavaBase;

public class UnionSplash implements ISplashAd,TTAdNative.SplashAdListener {
    static String Tag = "UnionSplash";
    final int AD_TIME_OUT = 5000;

    public UnionSplash(int priority) {
        m_Priority = priority;
        Activity activity = NJavaBase.getActivity();
        String UnionSplashId = "";
        try {
            ApplicationInfo appInfo = activity.getPackageManager().getApplicationInfo(
                    activity.getPackageName(), PackageManager.GET_META_DATA
            );

            UnionSplashId = appInfo.metaData.getString("UnionSplashId");
            if (UnionSplashId.length() > 0 && UnionSplashId.charAt(0) == '#')
                UnionSplashId = UnionSplashId.substring(1);

        } catch (PackageManager.NameNotFoundException e) {
            Log.e(Tag, "init error!");
            e.printStackTrace();
        }

        m_UnionSplashId = UnionSplashId;

        //强烈建议在合适的时机调用):申请部分权限，如read_phone_state,防止获取不了imei时候，下载类广告没有填充的问题。
        TTAdSdk.getAdManager().requestPermissionIfNecessary(activity);


        //等待一会儿才允许装载视频
        /*
        {
            Timer reloadTimer = new Timer();// 实例化Timer类
            class overTimeTask extends TimerTask {
                public void run() {
                    class reloadRunnable implements Runnable {
                        @Override
                        public void run() {
                            m_Initdone = true;
                        }
                    }
                    NJavaBase.getActivity().runOnUiThread(new reloadRunnable());
                    this.cancel();
                }
            }
            reloadTimer.schedule(new overTimeTask(), 500);// 毫秒
        }*/
    }


    //是否已经初始化完毕，可以开始加载
    public boolean isInitialized() {

        //return m_Initdone;
        return true;
    }

    //广告平台的名称
    public String adName() {
        return "UnionAd";
    }

    //预装 回调0表示预装成功 99表示预装失败
    public void show(ICallbackLight callBack) {
        if (m_Loading) return;
        m_Loading = true;
        m_Callback = callBack;
        this.load();
    }

    //优先级，值越大越优先
    public int getPriority() {
        return m_Priority;
    }


    void load() {
        Log.d(Tag, "start Load");
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(m_UnionSplashId)
                .setSupportDeepLink(true)
                .setImageAcceptedSize(1080, 1920)
                .build();
        TTAdNative adNative = TTAdSdk.getAdManager().createAdNative(NJavaBase.getActivity());
        adNative.loadSplashAd(adSlot, this, AD_TIME_OUT);

    }

    @Override
    //@MainThread
    public void onError(int code, String message) {
        m_Loading = false;
        Log.e(Tag, "load error : " + code + ", " + message);
        m_Callback.reCall(new Integer(99));

        Map<String,Object> param = new HashMap<>();
        param.put("v","err");
        NJavaBase.trackEvent("ad_splash",param);
    }

    @Override
    //@MainThread
    public void onTimeout() {
        m_Loading = false;
        Log.e(Tag, "开屏广告装载超时");
        m_Callback.reCall(new Integer(99));

        Map<String,Object> param = new HashMap<>();
        param.put("v","timeout");
        NJavaBase.trackEvent("ad_splash",param);
    }

    @Override
    //@MainThread
    public void onSplashAdLoad(TTSplashAd ad) {
        Log.d(Tag, "开屏广告请求成功");
        if (ad == null) return;

        final View adView = ad.getSplashView();
        final TTSplashAd tAd = ad;
        Activity activity = NJavaBase.getActivity();

        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT);
        layoutParams.gravity= Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL;
        activity.addContentView(adView,layoutParams);
        adView.setVisibility(View.VISIBLE);

        //设置SplashView的交互监听器
        ad.setSplashInteractionListener(new TTSplashAd.AdInteractionListener() {
            @Override
            public void onAdClicked(View view, int type) {
                Log.d(Tag, "onAdClicked");
            }

            @Override
            public void onAdShow(View view, int type) {
                Log.d(Tag, "onAdShow");
            }

            @Override
            public void onAdSkip() {
                Log.d(Tag, "onAdSkip");
                m_Loading = false;
                ViewGroup vg = (ViewGroup) adView.getParent();
                if(vg!=null) vg.removeView(adView);

                //通知关闭
                m_Callback.reCall(new Integer(3));

                Map<String,Object> param = new HashMap<>();
                param.put("v","skip");
                NJavaBase.trackEvent("ad_splash",param);
            }

            @Override
            public void onAdTimeOver() {
                Log.d(Tag, "onAdTimeOver");
                m_Loading = false;
                ViewGroup vg = (ViewGroup) adView.getParent();
                if(vg!=null) vg.removeView(adView);

                //可获得奖励
                m_Callback.reCall(new Integer(2));

                //通知关闭
                m_Callback.reCall(new Integer(3));

                Map<String,Object> param = new HashMap<>();
                param.put("v","reward");
                NJavaBase.trackEvent("ad_splash",param);
            }
        });
    }

    int m_Priority;
    String m_UnionSplashId;
    //TTAdNative m_AdNative;
    boolean m_Initdone = false;
    boolean m_Loading = false;
    ICallbackLight m_Callback;
}